package com.zhuang.designpattern.singleton;

import java.util.concurrent.atomic.AtomicReference;

/**
 * description: CAS「AtomicReference」(线程安全)
 * date: 2022/9/14 18:34
 * author: Zhuang
 * version: 1.0
 */
public class Singleton_06 {
    public static void main(String[] args) {
        Singleton06 instance1 = Singleton06.getInstance();
        Singleton06 instance2 = Singleton06.getInstance();

        System.out.println("instance1 = " + instance1);
        System.out.println("instance2 = " + instance2);
    }
}

class Singleton06 {

    private static final AtomicReference<Singleton06> INSTANCE = new AtomicReference<>();

    private static Singleton06 instance;

    private Singleton06() {

    }

    public static final Singleton06 getInstance() {
        while (true) {
            Singleton06 instance = INSTANCE.get();
            if (null != instance) return instance;
            INSTANCE.compareAndSet(null, new Singleton06());
            return INSTANCE.get();
        }
    }
}
